package com.simple.datax.transport.webservice;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import javax.jws.WebParam;
import javax.jws.WebService;

import org.apache.cxf.feature.Features;
import org.apache.log4j.Logger;

import com.simple.datax.transport.webservice.processor.WebServiceProcessor;

@WebService(endpointInterface = "com.simple.datax.transport.webservice.WebServiceConn", serviceName = "WebServiceConn")
public class WebServiceConnImpl implements WebServiceConn {
	private static final Logger logger = Logger.getLogger(WebServiceConnImpl.class);
//	public static boolean isFirstCall = true;
	private WebServiceProcessor processor;
	private static final String AUTH_FAILED = "鉴权失败";
	private static final String FILE_INVALID = "无效报文";
	private static final String SAVE_FAILED = "文件传送失败";
	private static final String LIST_FAILED = "文件列表获取失败";
	private static final String OPEN_FAILED = "文件传送失败";
	private static final String CALL_PARAM_ERROR = "服务最后一个参数必须在客户端初始化为非null对象，否则无法返回期望结果";
//	private static AtomicInteger count = new AtomicInteger();
//	private int index;
	
	public WebServiceConnImpl() {
//		index = count.incrementAndGet();
	}
	
	public String sendData(String user, String password, String message) {
//		logger.debug("WebServiceConnImpl Object: " + this.index);
//		if (this.index%2==1) {
//			try {
//				Thread.sleep(3000);
//			} catch (Exception ex) {
//				
//			}
//		}
		if (!processor.validate(user, password)) {
			return AUTH_FAILED;
		} else {
			if (message == null || message.trim().isEmpty()) {
				return FILE_INVALID;
			}
			if (processor.saveMessageFile(user, message)) {
//				logger.debug("get message: " + message);
			} else {
				logger.debug("Failed to save file. ");
				return SAVE_FAILED;
			}
		}
		return null;
	}
	
	public String getDataList(String user, String password,
			javax.xml.ws.Holder<List<String>> result) {
		if (result == null) {
			return CALL_PARAM_ERROR;
		}
		if (!processor.validate(user, password)) {
			return AUTH_FAILED;
		}
		try {
			result.value = processor.getDataList(user);
		} catch (Exception ex) {
			logger.error("getDataList error", ex);
			return LIST_FAILED;
		}
		return null;
	}

	public String getData(String user, String password,
			String messageId, javax.xml.ws.Holder<byte[]> result) {
		if (result == null) {
			return CALL_PARAM_ERROR;
		}
		if (!processor.validate(user, password)) {
			return AUTH_FAILED;
		}
		try {
			result.value = processor.getData(user, messageId);
		} catch (Exception ex) {
			logger.error("Failed to get data:", ex);
			return OPEN_FAILED;
		}
		return null;
	}

	public WebServiceProcessor getProcessor() {
		return processor;
	}

	public void setProcessor(WebServiceProcessor processor) {
		this.processor = processor;
	}
}
